﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Test14_02Server
{
    class Program
    {
        static void Main()
        {
            int port = 888;
            TcpClient tcpClient;
            IPAddress[] serverIP = Dns.GetHostAddresses("127.0.0.1");
            IPAddress localAddress = serverIP[0];
            TcpListener tcpListener = new TcpListener(localAddress, port);
            tcpListener.Start();
            Console.WriteLine("服务器启动成功，等待用户接入...");
            while (true)
            {
                try
                {
                    tcpClient = tcpListener.AcceptTcpClient();
                    NetworkStream networkStream = tcpClient.GetStream();
                    BinaryReader reader = new BinaryReader(networkStream);
                    BinaryWriter writer = new BinaryWriter(networkStream);
                    while (true)
                    {
                        try
                        {
                            string strReader = reader.ReadString();
                            string[] strReaders = strReader.Split(new char[] { ' ' });
                            Console.WriteLine("有客户端接入，客户IP：" + strReaders[0]);
                            Console.WriteLine("来自客户端的消息：" + strReaders[1]);
                            string strWriter = "我是服务器，欢迎光临";
                            writer.Write(strWriter);
                        }
                        catch
                        {
                            break;
                        }
                    }
                }
                catch
                {
                    break;
                }
            }
        }
    }
}
